package dao;

import java.util.List;
import java.util.ArrayList;

import org.hibernate.Session;
import org.hibernate.Query;

import trip.HibernateUtil;
import trip.Person;
import trip.Route;
import trip.Stop;

public class StopDAOImpl extends GenericDaoImpl<Stop> implements StopDAO {
	public StopDAOImpl(Class<Stop> type) {
		super(type);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Stop> getByName(String name) {
		Session session = null;
		List<Stop> result = new ArrayList<Stop>();
		if (name == null)
			return result;
		try {
			session = HibernateUtil.getFactory().openSession();
			session.beginTransaction();
			Query query = session.createQuery("select s from Stop s where s.name like :template");
			query.setString("template", "%" + name + "%");
			result = query.list();
			session.getTransaction().commit();
			return result;
		} finally {
			if (session != null && session.isOpen())
				session.close();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Stop> getByRoute(Route route) {
		Session session = null;
		List<Stop> result = new ArrayList<Stop>();
		if (route == null)
			return result;
		try {
			session = HibernateUtil.getFactory().openSession();
			session.beginTransaction();
			Query query = session.createQuery("select rs.stop from Route_stops rs "
					+ "where rs.route = :id order by rs.stop_number asc");
			query.setLong("id", route.getId());
			result = query.list();
			session.getTransaction().commit();
			return result;
		} finally {
			if (session != null && session.isOpen())
				session.close();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<List<Stop>> getByPerson(Person person) {
		Session session = null;
		List<List<Stop>> result = new ArrayList<List<Stop>>();
		List<Stop> dst = null, ast = null;
		if (person == null)
			return result;
		try {
			session = HibernateUtil.getFactory().openSession();
			session.beginTransaction();
			Query query = session.createQuery("select pt.departure_stop "
					+ "from Person_trip pt "
					+ "where pt.person = :id");
			query.setLong("id", person.getId());
			dst = query.list();
			query = session.createQuery("select pt.arrival_stop "
					+ "from Person_trip pt "
					+ "where pt.person = :id");
			query.setLong("id", person.getId());
			ast = query.list();
			session.getTransaction().commit();
			if (dst.size() != ast.size())
				return result;
			for(int i = 0; i < dst.size(); i++) {
				List<Stop> tmp = new ArrayList<Stop>();
				tmp.add(dst.get(i));
				tmp.add(ast.get(i));
				result.add(tmp);
			}
			return result;
		} finally {
			if (session != null && session.isOpen())
				session.close();
		}
	}
}
